<template>
    <list-layout>
        <div slot="search">
            <el-form :model="queryParams" :inline="true" ref="queryForm" v-show="showSearch" label-width="88px">
                <el-row>
                    <el-col :span="6">
                        <el-form-item :label="$t('basicData.materialSubType')" prop="typeCode">
                            <el-input v-model="queryParams.typeCode" :placeholder="$t('public.placeholder',{placeholder: '物料小类'})" clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <!--  <el-col :span="6">
                        <el-form-item label="类型名称" prop="typeName">
                            <el-input v-model="queryParams.typeName" :placeholder="$t('public.placeholder',{placeholder: '类型名称'})" clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="6">
                        <!--            物料大类-->
                        <el-form-item :label="$t('basicData.MaterialCategory')" prop="materialMax">
                            <el-select v-model="queryParams.materialMax" multiple filterable size="small" @change="handleMaterialMaxChange" reserve-keyword :placeholder="$t('public.selectPl')+'物料大类'">
                                <el-option v-for="item in dict.type.NYIQC_MATERIAL_MAX" :key="item.label" :label="item.label" :value="item.label">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" align="left">
                        <!--            物料中类：-->
                        <el-form-item :label="$t('basicData.materialClass')" prop="materialMiddle">
                            <el-select v-model="queryParams.materialMiddle" multiple filterable size="small" reserve-keyword :placeholder="$t('public.selectPl')+'物料中类'">
                                <el-option v-for="(item,index) in materialMiddleOptions" :key="index" :label="item" :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col align='center'>
                        <el-form-item class="right-btns">
                            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('public.query')}}</el-button>
                            <el-button icon="el-icon-refresh" class="resectBtn" size="mini" @click="resetQuery">{{$t('public.reset')}}</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

        </div>
        <div class="app-container">
            <div class="container-header">
                <div class="header-left">
                    物料小类
                </div>
            </div>
            <el-row :gutter="10" class="table-action-wrap btnGroup">
                <el-button type="primary" icon="el-icon-plus" size="mini" v-hasPermi="['masterdata:materialType:add']" @click="handleAdd">{{$t('public.add')}}</el-button>

                <el-button icon="el-icon-delete" size="mini" class="deleteitemBtn" v-hasPermi="['masterdata:materialType:delete']" @click="handleApproval">{{$t('public.delete')}}</el-button>

                <el-button class="importitemBtn" size="mini" @click="handleImport" v-hasPermi="['masterdata:materialType:import']"><img src="@/assets/images/icons/daoru.png" alt=""> {{$t('public.import')}}</el-button>

                <el-button class="exportitemBtn" size="mini" :loading="exportLoading" @click="handleExport" v-hasPermi="['masterdata:materialType:export']"><img src="@/assets/images/icons/daochu.png" alt=""> {{$t('public.export')}}</el-button>

            </el-row>
            <input v-show="false" ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx,xls" @change="handleClick">

            <div class="container-table">
                <el-table :height="tableHeight" border stripe v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">

                    <el-table-column type="selection" width="55" align="center" />
                    <!--          序号-->
                    <el-table-column :label="$t('public.serialNum')" type="index" width="55" align="center" />
                    <!--          物料大类-->
                    <el-table-column :label="$t('basicData.MaterialCategory')" align="left" prop="materialMax" minWidth="160" show-overflow-tooltip />
                    <!--          物料中类-->
                    <el-table-column :label="$t('basicData.materialClass')" align="left" prop="materialMiddle" minWidth="160" show-overflow-tooltip />
                    <!--          物料类型-->
                    <el-table-column :label="$t('basicData.materialSubType')" align="left" prop="typeCode" minWidth="160" show-overflow-tooltip />
                    <!--          类型名称-->`
                    <el-table-column :label="$t('basicData.materialSubTypeName')" align="left" prop="typeName" minWidth="160" show-overflow-tooltip />
                    <!--          描述-->
                    <el-table-column :label="$t('basicData.description')" align="left" prop="description" minWidth="160" show-overflow-tooltip />
                    <el-table-column :label="$t('public.opera')" fixed="right" align="center" width="160">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                <table-body-btn type="gwedit" v-hasPermi="['masterdata:materialType:edit']" @click.native="handleEdit(scope.row)" />
                                <table-body-btn type="gwdelete" v-hasPermi="['masterdata:materialType:remove']" @click.native="handleDelete(scope.row)" />
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
            </div>

            <!-- 新增|编辑｜查看 弹框 -->
            <detail :visible.sync="visible" v-model="form" :type="dialogType" @refresh="getList()"></detail>
            <import-dialog :visible.sync="materialVisible" @callback="getList()" :action="'/qcmasterdata/materialMin/import'" :templateUrl="'/static/materialType.xlsx'" />

        </div>
    </list-layout>
</template>
<script>
import {refreshCache} from '@/api/basic/dict/type'
import {delMaterialType, getMasterialMaxMinData, importMaterialType, listMaterialType,} from '@/api/basic/materialtype'
import {mapState} from 'vuex'
import Detail from './detial.vue'
import importDialog from '../../components/importDialog'
//基础数据-物料类型
export default {
    name: 'materialType',
    dicts: ['NYIQC_MATERIAL_MAX'],

    components: { Detail, importDialog },
    computed: {
        ...mapState({
            isFold: (state) => state.app.isFold,
        }),
    },
    watch: {
        isFold(val) {
            if (val === true) {
                this.tableHeight = 'calc(100vh - 308px)'
            } else {
                this.tableHeight = 'calc(100vh - 396px)'
            }
        },
    },
    data() {
        return {
            dialogType: 1, //1:新增  2：编辑 3：查看
            tableHeight: 'calc(100vh - 308px)',
            materialVisible: false,
            dialogForm: {},
            materialMaxOptions: [],
            materialMiddleOptions: [],
            materialTypeOptions: [],
            direction: 'rtl',
            addInspection: false,
            visible: false,
            drawer: false,
            approvalOpen: false,
            viewModel: {
                inspectionInformation: '0',
            },
            editModel: {
                inspectionInformation: '0',
            },
            approvalForm: {
                status: '1',
                textarea: '',
            },
            selBtn: 1,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 字典表格数据
            typeList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 20,
                typeCode: '',
                typeName: '',
                materialMax: [],
                materialMiddle: [],
            },
            // 表单参数
            form: undefined,
            exportLoading: false,
            fullscreen: false,
            names: [],
        }
    },
    created() {
        this.getList()
        this.getMaterialType({}, 'materialMax')
        this.getMaterialType({ materialMax: 'all' }, 'materialMiddle')
    },
    methods: {
        drawerClose() {
            this.drawer = false
        },
        getMaterialType(params, key) {
            let array = []
            getMasterialMaxMinData(params).then((res) => {
                array = res.data.map((item) => item[key])
                if (key === 'materialMax') this.materialMaxOptions = array
                else this.materialMiddleOptions = array
            })
        },
        filterParams(p) {
            if (p && p.length) {
                return p.join(',')
            } else {
                return ''
            }
        },
        /** 查询字典类型列表 */
        getList() {
            this.loading = true
            let params = JSON.parse(JSON.stringify(this.queryParams))
            params.materialMax = this.filterParams(params.materialMax)
            params.materialMiddle = this.filterParams(params.materialMiddle)
            console.log(params)
            listMaterialType(params).then((response) => {
                if (response.code == 200 && response.rows) {
                    this.typeList = response.rows
                    this.total = response.total
                    this.loading = false
                }
            })
        },
        handleMaterialMessageTypeChange(e) {
            console.log('无聊', e)
            this.queryParams.gaugeType = e.join(',')
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                dictId: undefined,
                dictName: undefined,
                dictType: undefined,
                status: '0',
                remark: undefined,
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.form = {}
            this.dialogType = 1
            this.visible = true
        },
        handleApproval() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.handleDelete()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.names = selection.map((item) => item.typeCode)
            // this.single = selection.length!=1
            // this.multiple = !selection.length
        },

        // materialTypeRemoteMethod(e) {
        //     listALLMaterialType({ materialTypeName: e }).then((res) => {
        //         this.materialTypeOptions = res.data
        //     })
        // },
        handleMaterialMaxChange(e) {
            this.getMaterialType(
                { materialMax: e.join(',') || 'all' },
                'materialMiddle'
            )
            if (this.queryParams.materialMiddle.length) {
                this.$set(this.queryParams, 'materialMiddle', [])
            }
        },
        handleMaterialMiddleChange(e) {
            this.queryParams.materialMiddle = e.join(',')
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const dictIds = (row && row.id) || this.ids
            const names = (row && row.typeCode) || this.names
            this.$modal
                .confirm('是否确认删除类型名称为"' + names + '"的数据项？')
                .then(function () {
                    return delMaterialType(dictIds)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess(this.$t('processDefinition.successfullyDeleted'))
                })
                .catch(() => {})
        },
        /** 查看按钮操作 */
        handleView(row) {
            this.dialogType = 3
            this.form = row
            this.visible = true
            // if(row.hasRead == 0){
            //   readNotice(row.noticeId).then(res=>{
            //     if(res.code == 200){
            //       this.handleQuery()
            //     }
            //   })
            // }
        },
        /** 编辑按钮操作 */
        handleEdit(row) {
            this.dialogType = 2
            this.form = row
            this.visible = true
        },
        /** 关闭抽屉操作 */
        handleClose(row) {
            this.drawer = false
        },
        // 导入
        handleImport() {
            this.materialVisible = true
            // this.$refs['excel-upload-input'].click()
        },
        async handleClick(e) {
            try {
                const formData = new FormData()
                formData.append('file', e.target.files[0])
                const res = await importMaterialTypeExcel(formData)
                if (res.code == 200) {
                    this.$message.success('导入成功')
                    this.getList()
                    this.$refs['excel-upload-input'].value = ''
                }
            } catch (error) {
                this.$refs['excel-upload-input'].value = ''
            }
        },
        /** 导出按钮操作 */
        handleExport() {
            // const queryParams = this.queryParams
            // this.$modal.confirm(this.$t('MaterialType.export')).then(() => {
            //   this.exportLoading = true
            //   return exportMaterialType(queryParams)
            // }).then(response => {
            //   this.$download.name(response.msg)
            //   this.exportLoading = false
            // }).catch(() => {})
            this.queryParams.materialMax =
                this.queryParams.materialMax.join(',')
            this.queryParams.materialMiddle =
                this.queryParams.materialMiddle.join(',')
            this.download(
                'masterdata/materialMin/export',
                {
                    ...this.queryParams,
                },
                `materialType_${new Date().getTime()}.xlsx`
            )
        },
        async handleClick(e) {
            try {
                const formData = new FormData()
                formData.append('file', e.target.files[0])
                const res = await importMaterialType(formData)
                if (res.code == 200) {
                    this.$message.success('导入成功')
                    this.getList()
                    this.$refs['excel-upload-input'].value = ''
                }
            } catch (error) {
                this.$refs['excel-upload-input'].value = ''
            }
        },
        /** 刷新缓存按钮操作 */
        handleRefreshCache() {
            refreshCache().then(() => {
                this.$modal.msgSuccess('刷新成功')
            })
        },
    },
}
</script>
<style lang="scss" scoped>
::v-deep .el-card {
    padding-top: 20px;
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    padding-bottom: 20px;
}
::v-deep .el-aside {
    padding: 0;
    margin-bottom: 0;
}
.content-style {
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 2px;
    background-color: white;
    margin-top: 10px;
}
::v-deep .el-button-group .selBtn {
    background: #fff;
    border: 1px solid #0b7be3;
    color: #0b7be3;
}
::v-deep .el-button-group .unselBtn {
    background: #fff;
    border: 1px solid #ededf2;
    color: #666666;
}
.header-left {
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    padding: 3px 0 10px;
    display: inline-flex;
    justify-content: center;
    border-bottom: 2px solid #0b7be3;
}
.header-right {
    float: right;
}
.container-header {
    border-bottom: 1px solid #ededf2;
}
.container-table {
    float: left;
    //margin-top:6px;
    width: 100%;
}
.mb8 {
    float: left;
    margin-top: 6px;
    width: 100%;
}
.drawer-footer {
    display: flex;
    position: relative;
    z-index: 9999;
    bottom: -40px;
    height: 40px;
    justify-content: center;
    width: 100%;
}
.drawer-close {
    background: #f7f8fa;
    border-color: #f7f8fa;
}

.right-btns ::v-deep .el-button {
    margin-top: 0;
}
.app-container {
    padding: 0;
}
.table-action-wrap {
    padding: 12px 0;
}
</style>
